package com.roc.web.action.settlemgr;

import java.io.InputStream;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import net.sf.json.JSONObject;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.roc.newPage.IPageService;
import com.roc.page.BaseSearchCondition;
import com.roc.page.PaginationBaseAction;
import com.roc.pojo.Operators;
import com.roc.pojo.TblSettleItem;
import com.roc.service.IExcelService;
import com.roc.service.setting.SettlementToPayAgainService;
import com.roc.util.Constance;
import com.roc.util.constant.Constant;
import com.roc.util.constant.PayStatus;
import com.roc.util.constant.Role;
@Component
@Scope("prototype")
@Namespace("/topayAgain")
public class SettlementToPayAgainAction extends PaginationBaseAction{
	private static final long serialVersionUID = 1L;
	private SettlementToPayAgainSearchCondition searchCondition;
	private static Logger logger = LogManager.getLogger(SettlementToPayAgainAction.class);
	private InputStream excelFile;
	@Autowired
	private IPageService pagenitionService;
	@Autowired
	private IExcelService excelService;
	private String againId;
	private String remark;
	@Autowired
	private SettlementToPayAgainService settlementToPayAgainService;
	@Autowired
	/**
	 * 初始化出款页面
	 * @return
	 */
	@Action(value="queryToPayAgainInit",results={@Result(name="success",location="/pages/settlementMoney/toPayAgainMoneyList.jsp"),
			@Result(name = "error", location = "/error.jsp")})
	public String queryToPayMoneyJsp(){
		Operators op = (Operators) getSession().getAttribute(
				Constant.SESSION_LOGIN_MERCHANT);
		if (op.getRoleType().equals(Role.CLEAR_OPERATORS.getCode())
				|| op.getRoleType().equals(Role.CLEAR_LEAD.getCode())
				|| op.getRoleType().equals(Role.SYSTEM.getCode())) {
				searchCondition=new SettlementToPayAgainSearchCondition();
				String today = Constance.currTime();
				searchCondition.setApplyDateMin(today);
				searchCondition.setApplyDateMax(today);
				return SUCCESS;
		}
		addActionError("无权限访问!!!");
		return ERROR;
	}
	/**
	 * 出款列表
	 * @return
	 */
	@Action(value="queryToPayAgainMoneyJsp",results={@Result(name="success",location="/pages/settlementMoney/toPayAgainMoneyList.jsp"),
			@Result(name = "error", location = "/error.jsp")})
	public String querySettlementMsgList(){
		try {
			Operators op = (Operators) getSession().getAttribute(
					Constant.SESSION_LOGIN_MERCHANT);
			if (op.getRoleType().equals(Role.CLEAR_OPERATORS.getCode())
					|| op.getRoleType().equals(Role.CLEAR_LEAD.getCode())
					|| op.getRoleType().equals(Role.SYSTEM.getCode())) {
				if(searchCondition == null){
					searchCondition = (SettlementToPayAgainSearchCondition) getSearchConditionFromSession();
					if(searchCondition == null){
						searchCondition = new SettlementToPayAgainSearchCondition();
					}
				}			
				int rows=pagenitionService.countSQL(searchCondition);
				if(rows>0){
					searchRsList=pagenitionService.findAllSQL(searchCondition, calcuStart(getCurrentPage()), Constance.PAGE_MAX_SIZE);
				}
				
				List<TblSettleItem> settleList = new ArrayList<TblSettleItem>();
				dealTheSearchRsList(searchRsList,settleList);
				addActionMessage("当前条件下统计到【"+rows+"】条记录");
				getRequest().setAttribute("settleList", settleList);
				this.setTotalPage(this.calcuTotalPage(rows));
				getRequest().setAttribute(CURRENT_PAGE, this.getCurrentPage());
				getRequest().setAttribute(TOTAOL_PAGE, this.getTotalPage());
				setSearchToConditionSession(searchCondition);
				return SUCCESS;
			}
			addActionError("无权限访问!!!");
		} catch (Exception e) {
			logger.error("出款查询异常",e);
			addActionError("出款查询异常");
			return ERROR;
		}
		return ERROR;
	}
	private void dealTheSearchRsList(List<Object> searchRsList,
			List<TblSettleItem> settleList) throws Exception {
		try {
			if(searchRsList != null && searchRsList.size() > 0){
				Iterator<Object> it = searchRsList.iterator();
				while(it.hasNext()){
					Object[] obj = (Object[]) it.next();
					TblSettleItem bean = new TblSettleItem();
					bean.setId(Long.parseLong(Constance.Null2EmptyTrim(obj[0])));
					bean.setInsIdCd(Constance.Null2EmptyTrim(obj[1]));
					bean.setMchtCd(Constance.Null2EmptyTrim(obj[2]));
					bean.setMchtName(Constance.Null2EmptyTrim(obj[3]));
					String transAmt = Constance.Null2EmptyTrim(obj[4]);
					if(!"".equals(transAmt)){
						bean.setTransAmt(Double.parseDouble(transAmt));
					}else{
						bean.setTransAmt(0.00);
					}
					String totalNum = Constance.Null2EmptyTrim(obj[5]); 
					if(!"".equals(totalNum)){
						bean.setTotalNum(Integer.parseInt(totalNum));
					}else{
						bean.setTotalNum(0);
					}
					String mchtFee = Constance.Null2EmptyTrim(obj[6]);
					if(!"".equals(mchtFee)){
						bean.setMchtFee(Double.parseDouble(mchtFee));
					}else{
						bean.setMchtFee(0.00);
					}
					String setAmt = Constance.Null2EmptyTrim(obj[7]);
					if(!"".equals(setAmt)){
						bean.setMchtSetAmt(Double.parseDouble(setAmt));
					}else{
						bean.setMchtSetAmt(0.00);
					}
					bean.setBankName(Constance.Null2EmptyTrim(obj[8]));
					bean.setBankCode(Constance.Null2EmptyTrim(obj[9]));
					bean.setAccount(Constance.Null2EmptyTrim(obj[10]));
					bean.setAccountName(Constance.Null2EmptyTrim(obj[11]));
					bean.setAccType(Constance.Null2EmptyTrim(obj[12]));
					bean.setSettleDate(Constance.Null2EmptyTrim(obj[13]));
					bean.setSettleFlag(PayStatus.valueOfCode(Constance.Null2EmptyTrim(obj[14])).getName());
					bean.setSetDate(Constance.Null2EmptyTrim(obj[15]));
					bean.setFreezeFlag(Constance.Null2EmptyTrim(obj[16]));
					String freezeAmt = Constance.Null2EmptyTrim(obj[19]);
					if(!"".equals(freezeAmt)){
						bean.setFreezeAmt(Double.parseDouble(freezeAmt));
					}else{
						bean.setFreezeAmt(0.00);
					}
					String unfreezeAmt = Constance.Null2EmptyTrim(obj[20]);
					if(!"".equals(unfreezeAmt)){
						bean.setUnFreezeAmt(Double.parseDouble(unfreezeAmt));;
					}else{
						bean.setUnFreezeAmt(0.00);
					}
					bean.setRemark1(Constance.Null2EmptyTrim(obj[21]));
					bean.setRemark(Constance.Null2EmptyTrim(obj[22]));
					bean.setIsCombing(Constance.Null2EmptyTrim(obj[23]));
					bean.setSerialNo(Constance.Null2EmptyTrim(obj[24]));
					if(obj[25]==null||obj[25]==""){
						bean.setCount(0);
					}else{
						bean.setCount(Integer.parseInt(Constance.Null2EmptyTrim(obj[25])));
					}
					bean.setChangeFlag(Constance.Null2EmptyTrim(obj[26]));
					bean.setRemark5(Constance.Null2EmptyTrim(obj[27]));
					if(obj.length>28){
						bean.setReason(Constance.Null2EmptyTrim(obj[28]));
					}
					settleList.add(bean);
				}
			}
		}catch (Exception e) {
			throw new Exception("解析数据封装到出款信息实体类异常");
		}
	}
	
	/**
	 * 补付操作
	 * @return
	 */
	@Action(value="updatePayStatus")
	public void updatePayStatus(){
		Operators op = (Operators) getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		PrintWriter pw = null;
		JSONObject json = new JSONObject();
		try {
			getResponse().setCharacterEncoding("utf-8");
			pw = getResponse().getWriter();
			logger.info(op.getRealName()+"开始补付流水号为"+againId+"的出款记录");
			settlementToPayAgainService.updateStatus(againId,op);
			json.put("flag", true);
			pw.write(json.toString());
		} catch (Exception e) {
			json.put("flag", false);
			pw.write(json.toString());
			logger.error("补付失败");
			logger.error(e.getMessage(),e);
		}finally{
			if(pw != null){
				pw.close();
			}
		}
	}
	@Action(value="queryToPayAgainFailInfoJsp",results={@Result(name="success",location="/pages/settlementMoney/toPayAgainFailInfoList.jsp"),
			@Result(name = "error", location = "/error.jsp")})
	public String payAgainInfo() throws Exception{
		try{
			searchRsList= settlementToPayAgainService.queryPayFailList(remark);
			List<TblSettleItem> settleList = new ArrayList<TblSettleItem>();
			dealTheSearchRsList(searchRsList,settleList);
			getRequest().setAttribute("settleList", settleList);
			return SUCCESS;
		}catch(Exception e){
			logger.info(e.getMessage());
			return ERROR;
		}
		
	}

	@Override
	protected BaseSearchCondition getSearchConditionFromSubClass()
			throws Exception {
		return searchCondition;
	}

	@Override
	protected void setSearchConditionToSubClass(
			BaseSearchCondition searchCondition) throws Exception {
		this.setSearchConditionToSubClass(searchCondition);
	}

	@Override
	protected void setSearchToConditionSession(
			BaseSearchCondition searchCondition) {
		getSession().setAttribute(SEARCH_SESSION_TO_PAY_AGAIN_QUERY, searchCondition);
	}

	@Override
	protected BaseSearchCondition getSearchConditionFromSession() {
		return (SettlementToPayAgainSearchCondition)getSession().getAttribute(SEARCH_SESSION_TO_PAY_AGAIN_QUERY);
	}

	@Override
	protected String getInitPageSize() {
		return Constance.PAGE_MAX_SIZE+"";
	}

	public SettlementToPayAgainSearchCondition getSearchCondition() {
		return searchCondition;
	}

	public void setSearchCondition(
			SettlementToPayAgainSearchCondition searchCondition) {
		this.searchCondition = searchCondition;
	}
	public InputStream getExcelFile() {
		return excelFile;
	}
	public void setExcelFile(InputStream excelFile) {
		this.excelFile = excelFile;
	}
	
	public String getExcelName() {
		String excelName = "出款信息" + Constance.formateDate();

		try {
			excelName = new String(excelName.getBytes(), "ISO8859-1");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			logger.info("生成excel名称失败了！");
		}

		return excelName;
	}
	public String getAgainId() {
		return againId;
	}
	public void setAgainId(String againId) {
		this.againId = againId;
	}
	public String getRemark() {
		return remark;
	}
	public void setRemark(String remark) {
		this.remark = remark;
	}
	
	
}
